<template>
  <div class="article_all">
    <el-page-header
      @back="goBack"
      content="网站子页面"
      style="margin-bottom: 20px"
    ></el-page-header>

    <div class="article_head">
      <div class="article_head_left">
        <el-button
          class="addArticle"
          icon="el-icon-plus"
          @click="addSubpageMethod"
          >添加子页面</el-button
        >
        <el-input placeholder="搜索" v-model="searchInput" clearable></el-input>
      </div>
    </div>
    <div style="width: 100%">
      <div class="article_body">
        <el-table
          :data="searchDate"
          style="overflow-y: auto; margin-top: 16px; font-size: 14px"
          height="450"
          :header-cell-style="{ background: '#EBEEF2' }"
          :row-style="{ height: '80px' }"
        >
          <el-table-column prop="sitePic" label="页面图片" min-width="150">
            <template slot-scope="scope">
              <img
                :src="scope.row.sitePic.replace('dist/', '')"
                min-width="70"
                height="70"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="siteName"
            label="子页面名"
            min-width="150"
          ></el-table-column>
          <el-table-column
            prop="createName"
            label="创建人"
            min-width="150"
          ></el-table-column>
          <el-table-column prop="siteUrl" label="路径" min-width="120">
            <template slot-scope="scope">
              <a
                :href="scope.row.siteUrl.replace('dist/', '')"
                target="_blank"
                style="text-decoration: none; color: #6e5eff"
                >{{ scope.row.siteUrl }}</a
              >
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="250px">
            <template class="btnStyle" slot-scope="scope">
              <el-button
                @click="editWebsite(scope.row.id, scope.row.siteUrl)"
                icon="el-icon-monitor"
                circle
              ></el-button>
              <el-button
                @click="handleEdit(scope.$index, scope.row)"
                icon="el-icon-edit"
                circle
              ></el-button>
              <el-button
                @click="handleDel(scope.$index, scope.row)"
                icon="el-icon-delete"
                circle
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <el-pagination
          :current-page.sync="currentPage"
          :page-size.sync="pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[5, 10, 20, 50, 100]"
          layout="prev, pager, next, sizes , total"
          :total="total"
          style="margin-top: 5px"
        />
      </div>
    </div>

    <SubpageDialog
      :dialogFormVisible.sync="dialogFormVisible"
      :websiteInfo="websiteInfo"
      :mainPageId="mainPage.id"
      @refresh="getSubpageInfo"
    />

    <div class="loading" v-load:[loadText]="loading" />
  </div>
</template>

<script>
import {
  delSubpage,
  postSiteList,
  getSubpage,
} from "@/api/api.js";
import axios from "axios";
import SubpageDialog from "../components/SubpageDialog.vue";

export default {
  name: "Laucher",
  data() {
    return {
      countDown: 5,
      timer: null,
      searchInput: "",
      loadText: "加载中···",
      loading: false,
      tableHead: [
        { label: "文章标题", prop: "title", width: "120px" },
        { label: "分类", prop: "type", width: "100px" },
        { label: "发布时间", prop: "publicTime", width: "120px" },
        { label: "浏览权限", prop: "viewPermission", width: "50px" },
        { label: "链接", prop: "link", width: "50px" },
        { label: "浏览数", prop: "viewCount", width: "50px" },
      ],
      mainPage: [],
      selectedItems: [],
      showControls: false,
      dialogVisible: false,
      currentPage: 1,
      pageSize: 5,
      total: 10,
      websiteInfo: {
        siteLogo: "",
        siteName: "",
        sitePic: "",
        siteUrl: "",
      },
      dialogFormVisible: false,
    };
  },
  async created() {
    // 获取站点默认页面
    const res = await postSiteList(this.$route.query.id);
    if (res.data.result) {
      this.selectedItems.push(res.data.result);
      this.mainPage = res.data.result;
    }

    // 获取站点子页面
    this.getSubpageInfo();
  },
  methods: {
    // 获取子页面信息
    async getSubpageInfo() {
      try {
        const res = await getSubpage({
          pageNo: this.currentPage,
          pageSize: this.pageSize,
          sort: "updateAt",
          sortType: "desc",
        });
        // records是子页面列表,当其siteId和mainPage.id相等时，才将数据添加进selectedItems
        if (res.data.code === 200) {
          const temp = res.data.result.records.filter(
            (item) => item.siteId === this.mainPage.id
          );
          if (this.currentPage === 1) {
            let temp0 = this.mainPage;
            this.selectedItems = [];
            this.selectedItems.push(temp0);
            this.selectedItems.push(...temp);
            this.total = res.data.result.total;
          } else {
            this.selectedItems = [];
            this.selectedItems.push(...temp);
            this.total = res.data.result.total;
          }
        }
      } catch (error) {
        console.error(error);
      }
    },
    // 编辑网站子页面
    async editWebsite(id, path) {
      console.log(id, path);
      // 对path进行处理，获取相对路径
      const relativePath = path.replace("dist/", "");

      // 跳转到/Main/editor页面
      this.$router.push("/Main/editor");

      setTimeout(async () => {
        // 获取在/public/template/index.html中的html代码
        await this.load(relativePath);
      }, 300);
    },
    // 加载html
    load(path) {
      this.loading = true;
      axios
        .get(path, {
          headers: {
            accept: "text/html;charset=UTF-8",
          },
          params: {},
        })
        .then((res) => {
          this.$store.commit("setHomepageHTML", res.data);
          this.$store.commit("triggerForceImport");
          this.$nextTick(() => {
            this.loading = false;
          });
        })
        .catch((err) => {
          console.error(err);
          this.$nextTick(() => {
            this.loading = false;
          });
        });
    },
    // 添加子页面
    addSubpageMethod() {
      this.websiteInfo = {
        siteLogo: "",
        siteName: "",
        sitePic: "",
        siteUrl: "",
      };
      this.dialogFormVisible = true;
    },
    // 修改子页面
    handleEdit(index, row) {
      // 将选中的子页面信息赋值给websiteInfo
      this.websiteInfo = { ...row };
      this.dialogFormVisible = true;
    },
    // 删除子页面
    handleDel(index, row) {
      this.$confirm("此操作将永久删除该子页面, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const res = await delSubpage(row.id);
            if (res.data.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.selectedItems.splice(index, 1);
              this.getSubpageInfo();
            }
          } catch (error) {
            console.error(error);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.getSubpageInfo();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.getSubpageInfo();
    },
    goBack() {
      this.$router.go(-1);
    },
  },
  computed: {
    searchDate() {
      // 这里之后对接后端
      return this.selectedItems.filter((item) =>
        item.siteName.includes(this.searchInput)
      );
    },
  },
  components: {
    SubpageDialog,
  },
};
</script>

<style scoped>
.article_all {
  text-align: center;
  margin: 20px;
}
.article_head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}
.addArticle {
  background-color: #7e72f2;
  color: white;
  border-radius: 10px;
  margin-right: 10px;
}
.addArticle:hover {
  color: #ebeafc;
}
.article_head_left,
.article_head_right {
  display: flex;
  align-items: center;
}
.article_head_right {
  flex-wrap: wrap;
}
.article_head_left ::v-deep .el-input--suffix .el-input__inner {
  border-radius: 10px;
  box-shadow: 0 0 1px #7e72f2;
}
.control_button {
  min-width: 20px;
  min-height: 20px;
  max-width: 20px;
  max-height: 20px;
  margin-right: 20px;
  cursor: pointer;
}
.pagination ::v-deep .el-pagination .el-pager .number.active {
  background-color: #7e72f2 !important;
  border-color: #7e72f2 !important;
  color: white !important;
}
.pagination ::v-deep .el-pagination .el-pager .number {
  color: #7e72f2 !important;
}
.pagination ::v-deep .el-pagination {
  position: relative;
}
.pagination {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: right;
}
.btnStyle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-left: 0;
}
.loading {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 999;
}
</style>
